﻿using System;

using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using Toolbox.util;

namespace Toolbox
{
    public partial class UdpForm : Form
    {
        static UdpClient udpClient;

        // UDP停止标识
        static bool stopBool = true;

        // 监听线程
        static Thread thread;

        public UdpForm()
        {
            InitializeComponent();

            // 在其他线程中可以调用主窗体控件
            CheckForIllegalCrossThreadCalls = false;
        }

        private void UdpForm_Load(object sender, EventArgs e)
        {
            // 获取本机名称
            string localName = Dns.GetHostName();
            textBox1.Text = localName;

            // 获取所有IP地址
            IPAddress[] ips = Dns.GetHostAddresses(localName);
            string localIp = "127.0.0.1";
            foreach (IPAddress ip in ips)
            {
                if (!ip.IsIPv6SiteLocal)
                {
                    localIp = ip.ToString();
                }
            }
            textBox1.Text = localIp;
            textBox5.Text = "255.255.255.255:6666";

            

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 打开/关闭服务器按钮
            if (button1.Text == "打开")
            {
                stopBool = true;
                string portStr = textBox2.Text;
                
                if (portStr.Length < 1)
                {
                    MessageBox.Show("请输入端口！");
                    return;
                }

                int port = int.Parse(portStr);

                // 检测端口是否占用
                bool portUsed = NetUtils.portInUse(port, "UDP");
                if (portUsed)
                {
                    MessageBox.Show("端口已被占用！", "警告");
                    return;
                }

                udpClient = new UdpClient(port);

                // 设置接收缓冲区大小
                udpClient.Client.ReceiveBufferSize = 1000000000;
                // 设置发送缓冲区大小
                udpClient.Client.SendBufferSize = 1000000000;


                // 创建IPEndPoint对象，用来显示响应主机的标识
                IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, port);

                thread = new Thread(() => {
                    while (stopBool)
                    {
                        try
                        {
                            // 判断是否有网络数据
                            if (udpClient.Available <= 0) continue;

                            // 判断连接是否为空
                            if (udpClient.Client == null) return;

                            // 调用UdpClient对象的Receive方法获得从远程主机返回的UDP数据报
                            byte[] bytes = udpClient.Receive(ref iPEndPoint);
                            Console.WriteLine("==============");
                            Console.WriteLine($"远程IP={iPEndPoint.Address}，端口={iPEndPoint.Port}");
                            Console.WriteLine("==============");

                            string str = HexUtils.bytesToHexStr(bytes);
                            textBox3.AppendText(HexUtils.spaceHexStr(str) + Environment.NewLine);
                        }
                        catch(Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }

                        //Thread.Sleep(100);
                    }
                });
                thread.Start();

                button1.Text = "关闭";
            }
            else
            {
                stopBool = false;

                // 终止线程
                if (thread.ThreadState == ThreadState.Running) thread.Abort();
                
                // 关闭连接
                udpClient.Close();

                button1.Text = "打开";
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            // 发送按钮
            string ipPort = textBox5.Text;
            if (ipPort.Length < 5 || !ipPort.Contains(":"))
            {
                MessageBox.Show("请输入远程IP和端口");
                return;
            }

            if(udpClient == null || !stopBool)
            {
                MessageBox.Show("UDP服务器已关闭！");
                return;
            }

            char[] separator = { ':' };
            string[] array = ipPort.Split(separator, StringSplitOptions.RemoveEmptyEntries);

            string text = textBox4.Text;
            if (text.Length == 0) return;

            byte[] data = HexUtils.hexStrToBytes(text);

            udpClient.Send(data, data.Length, new IPEndPoint(IPAddress.Parse(array[0]), int.Parse(array[1])));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 清除接收
            textBox3.Clear();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            // 清除发送
            textBox4.Clear();
        }

        private void UdpForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            stopBool = false;

            // 终止线程
            if (thread.ThreadState == ThreadState.Running) thread.Abort();

            // 关闭连接
            udpClient.Close();

            button1.Text = "打开";
        }
    }
}
